<?php
class adm extends page {
	public $page_title = 'Admin';

	public function load()
	{
		if(!$this->user->isFounder())
			return $this->error->e404();
		header('Pragma: no-cache');
		//require_once SVNCLIENT;
		$this->html->name = 'adm';
		//$this->html->cache = false;
		$this->layout = 'adm';
		$this->html->link('admin');
		$this->html->mootools(array('DomReady', 'Element.Event', 'Selectors', 'Class', 'Fx.SmoothScroll', 'Element.Shortcuts','Fx.Tween'));
		$this->html->js(array('admin', 'moocheck'));

		$opt = request_var('value1',false,'string');

		$spagisel = 'A';

		switch(request_var('form-name'))
		{
			case "edituser":
				$this->user->setUserData(request_var('value2', false, 'string'), request_var('edituser', array(), 'array'));
				redirect('/adm');
			break;

			case "followseria":
				if($data = request_var('followseria', false, 'array'))
				{
					$this->setFollow($data['user_id'], $data['series_id'], 'add');
				}
				redirect('/adm/edituser/' . request_var('value2', false, 'string'));
			break;

			case "editseria":
				if($data = request_var('editseria', false, 'array'))
				{
					$this->updateSeria($data);
				}
				global $db;
				redirect('/adm/editseria/' . request_var('value2', false, 'string'));
			break;

			case "batchepisodes":
				if($data = request_var('batchepisodes', false, 'array'))
				{
					switch($data['operation'])
					{
						case "del":
							$this->batchEpisodeDel($data['id']);
						break;
					}
				}
				redirect('/adm/editseria/' . request_var('value2', false, 'string'));
			break;

			case "settings":
				if($data = request_var('settings', false, 'array'))
				{
					if(is_array($data) && count($data))
					foreach($data as $key => $date)
						$this->settings->$key = $date;
				}
				redirect("/adm/");
			break;
		}

		switch($opt)
		{
			case "svn":
				$this->template->assign('svnout', implode("\n", $this->svnUpdate()));
			break;

			case "db":
				ob_start();
					new DBUpdater;
				$this->template->assign('dbout', ob_get_contents());
				ob_end_clean();
			break;

			case "deluser":
				$this->user->removeUserData(request_var('value2', false, 'string'));
				redirect('/adm');
			break;

			case "edituser":
				$data = $this->user->listUsers(request_var('value2', false, 'string'));
				$this->template->assign(array(
					'edituser' => $data,
					'userseries' => $this->userSeries(request_var('value2', false, 'string')),
					'ucanfollow' => $this->getSeriesToFollow(request_var('value2', false, 'string'))
				));
			break;

			case "delfollow":
				$this->setFollow(request_var('value2', false, 'string'), request_var('value3', false, 'string'), 'remove');
				redirect('/adm/edituser/'. request_var('value2', false, 'string'));
			break;

			case "spagi":
				$spagisel = request_var('value2', 'A');
			break;

			case "editseria":
				$this->page_title .= ' &bull; Sorozat szerkesztése';
				$this->layout = 'adm_editseria';
				$tv = new thetvdb;
				if(!$data = $tv->getSeria(request_var('value2', false, 'string')))
					return $this->error->e403();
				$this->template->assign(array(
					'seria' => $data['serie'],
					'episodes' => $data['episodes']
				));
				return;
			break;

			case "updateseria":
				$tv = new TheTvDB;

				$result = $tv->updateSeriesById(request_var('value2', false, 'int'));
				$this->template->assign('dbout', print_r($result, true));
			break;

			case "delseria":
				if($id = request_var('value2', false, 'int'))
				{
					$tv = new TheTvDB;
					$tv->removeSeriesById($id);
				}
				redirect($_SERVER['HTTP_REFERER']);
			break;

			case "emptycache":
				$this->emptyCache("*.*");
				redirect($_SERVER['HTTP_REFERER']);
			break;

		}

		$this->template->assign(array(
			//'latestversion' => $this->latestVersion(),
			'users' => users::listUsers(),
			'series' => $this->getSeriesList($spagisel),
			'abc' => array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','1'),
			'spagisel' => $spagisel
		));

	}

	private function latestVersion()
	{
		if($this->settings->version_check > strtotime('-1 day'))
			return array('version' => $this->settings->latest_version, 'date' => $this->settings->latest_date);
		$svn  = new phpsvnclient;

		$svn->setRespository(REPOSTORY);

		$data = $svn->getRepositoryLogs(-2,-2);
		$this->settings->latest_version = $svn->_repVersion;
		$this->settings->latest_date = $svn->_repDate;
		$this->settings->version_check = time();

		return array('version' => $this->settings->latest_version, 'date' => $this->settings->latest_date);
	}

	private function svnUpdate(){

		$svn  = new phpsvnclient;

		$svn->setRespository(REPOSTORY);

		$svn->getRepositoryLogs(-2,-2);

		$this->settings->version = $svn->_repVersion;
		$this->settings->date = $svn->_repDate;

		if(!WORKING_COPY)
			return $svn->update("/trunk/","./", $this->settings->version, -1);
	}

	private function userSeries($id){
		global $db;
		$sql = "SELECT s.`id`, s.`seriesname`, s.`firstaired` FROM `" . FOLLOWS_TABLE . "` f LEFT JOIN `" . SERIES_TABLE . "` s ON s.id = f.`series_id` WHERE f.`user_id` = '{$id}' and s.`seriesname` IS NOT NULL ORDER BY s.`seriesname` ASC";
		if($db->query($sql) && $db->affected_rows())
		{
			$result = $db->fetch_assoc();
			return $result;
		}

		return array();
	}

	public function setFollow($uid, $seria_id, $operation){
		global $db;
		$sql = "";

		switch($operation)
		{
			case 'remove':
				$sql = "DELETE FROM `" . FOLLOWS_TABLE . "` WHERE `user_id` = '{$uid}' and `series_id` = '{$seria_id}'";
			break;

			case 'add':
				$sql = "INSERT INTO `" . FOLLOWS_TABLE . "` (`user_id`, `series_id`) VALUES ('{$uid}', '{$seria_id}')";
			break;
		}

		return (bool)$db->query($sql);
	}

	public function getSeriesToFollow($id)
	{
		global $db;

		$sql = "SELECT s.`id`, CONCAT(s.`seriesname`, IF(s.`firstaired` != '0000-00-00', CONCAT(' (', DATE_FORMAT(s.`firstaired`, '%Y'), ')'), '')) as `s` FROM `" . SERIES_TABLE . "` s LEFT JOIN `" . FOLLOWS_TABLE ."` f ON f.series_id = s.id WHERE f.`user_id` != '{$id}' or f.`user_id` IS NULL ORDER BY s.`seriesname` ASC";
		if($db->query($sql) && $db->affected_rows())
		{
			$rows = $db->fetch_assoc();
			$out = array();
			foreach($rows as $row)
			{
				$out[$row['id']] = $row['s'];
			}
			return $out;
		}
		return array();
	}

	private function getSeriesList($letter)
	{
		global $db;
		switch($letter)
		{
			case "1":
				$filter = "s.`seriesname` REGEXP '^[^a-zA-Z]'";
			break;

			default:
				$filter = "s.`seriesname` LIKE '{$letter}%'";
			break;
		}

		$sql = "SELECT s.`id`, s.`seriesname`, s.`firstaired`, s.`status`, s.`last_updated`, (SELECT `combined_season` FROM `" . EPISODES_TABLE . "` WHERE `seriesid` = s.`id` ORDER BY `combined_season` DESC LIMIT 1) as `seasons` FROM `" . SERIES_TABLE . "` s WHERE {$filter} ORDER BY s.`seriesname` ASC";

		if($db->query($sql) && $db->affected_rows())
		{
			return $db->fetch_assoc();
		}
		return array();
	}

	private function updateSeria($data)
	{
		global $db;

		return $db->update_array(SERIES_TABLE, $data, array('id'));
	}

	private function batchEpisodeDel(array $ids)
	{
		global $db;
		$sql = "DELETE FROM `" . EPISODES_TABLE . "` WHERE `id` IN (";
		foreach($ids as $id)
		{
			$sql .= "{$id}";

			if(end($ids) != $id)
				$sql .= ", ";
		}
		$sql .= ")";
		return $db->query($sql);
	}

	private function emptyCache($file)
	{
		$match = glob(CACHE_DIR . $file);
		if(is_array($match) && count($match))
		foreach($match as $m)
		{
			if(file_exists($m))
				@unlink($m);
		}
	}

}
?>